package com.jing.android.util;

import java.io.File;
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class PermissionCheckUtils {

    private static final String MANIFEST_FILE_NAME = "AndroidManifest.xml";

    private static final String PERMISSION_RECEIVE_BOOT_COMPLETED = "RECEIVE_BOOT_COMPLETED";

    private static final int BUFFER_SIZE = 2048;

    public static void main(String[] args) {
        findPermissionInFolder(new File("/Users/jingtuo/.gradle/caches/modules-2/files-2.1"),
                new String[]{PERMISSION_RECEIVE_BOOT_COMPLETED});
        findPermissionInFolder(new File("/Users/jingtuo/Projects/Foundersc/xf_20210105"), new String[]{PERMISSION_RECEIVE_BOOT_COMPLETED});
    }

    public static void findPermissionInFolder(File folder, String[] permissions) {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File item : files) {
                if (item.isFile()) {
                    String fileName = item.getName();
                    if (fileName.endsWith(".aar")) {
                        findPermissionInAarFile(item, permissions);
                    }
                } else {
                    findPermissionInFolder(item, permissions);
                }
            }
        }
    }

    public static void findPermissionInAarFile(File aarFile, String[] permissions) {
        try {
            ZipInputStream zis = new ZipInputStream(new FileInputStream(aarFile));
            byte[] buffer = new byte[BUFFER_SIZE];
            StringBuilder builder = new StringBuilder();
            while( true) {
                ZipEntry entry = zis.getNextEntry();
                if (entry == null) {
                    break;
                }
                String entryName = entry.getName();
                if (!MANIFEST_FILE_NAME.equals(entryName)) {
                    continue;
                }
                while(true) {
                    int length = zis.read(buffer, 0, BUFFER_SIZE);
                    if (length == -1) {
                        break;
                    }
                    builder.append(new String(buffer, 0, length));
                }
                zis.closeEntry();
                String manifestContent = builder.toString();
                for (String permission: permissions) {
                    if (manifestContent.contains(permission)) {
                        System.out.println("find permission: " + permission + " in file: " + aarFile.getAbsolutePath());
                        System.out.println(manifestContent);
                    }
                }
                break;
            }
            zis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
